package com.example.demo.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.example.demo.entity.Student;
import com.example.demo.entity.TableData;
import com.example.demo.utils.OfficeWaterMarkUtil;
import com.example.demo.utils.WordUtils;

import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping
public class WordController {

    /***
     * 功能描述:
     * 根据用户ID更新ws推送的参数
     * @Date: 2022-12-01 09:21:25
     * @return: void
     * @since: 1.0.0
     */
    @RequestMapping("/download")
    public void download(HttpServletResponse response){
        Student student1 = new Student("一年级","一班","张三","班长");
        Student student2 = new Student("一年级","一班","李四","班长");
        Student student4 = new Student("一年级","二班","赵六","班长");
        Student student5 = new Student("二年级","一班","","班长");
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student4);
        list.add(student5);

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("students",list);

        String templateName = "moban.ftl";
        //这里注意一定得是doc，用doc可能会出现wps可以打开但是office打不开的情况，具体原因未知
        try {
            WordUtils.generateWord(dataMap, templateName, "D://work//demo.doc");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping(value = "/table")
    @SneakyThrows
    public void table(TableData tableData, HttpServletResponse response) {

        /* 假数据 */
        tableData.setTest("附件1-报价明细表");
        String[][] strings = new String[10][5];
        for (int i = 0; i < 10; i++) {
            strings[i] = new String[]{"1", "EREWHON", "生猪", "酒鬼酒", "125"};
        }
        tableData.setTableList(strings);

        // 模版路径
        String wordPath = getTemplateAbsolutePath("templates/wordmoban.docx");
//        String modelName = "表格.docx";

        // 手绘表格
        // 表头
        RowRenderData row0 = Rows.of("项号", "编号", "种类", "", "价格").center().create();
        RowRenderData row1 = Rows.of("项号", "编号", "期货", "股票", "价格").center().create();

        int length = 0;
        if (tableData.getTableList() != null) {
            length = tableData.getTableList().length;
        }
        // 表格数据 加上2行表头 再加上最后一行总价
        RowRenderData[] rowRenderData = new RowRenderData[length + 3];
        rowRenderData[0] = row0;
        rowRenderData[1] = row1;
        // 计算价钱
        BigDecimal totalPrice = new BigDecimal("0");
        for (int i = 0; i < length; i++) {
            rowRenderData[i + 2] = Rows.of(tableData.getTableList()[i]).center().create();
            String s = tableData.getTableList()[i][4];
            BigDecimal bigDecimal = new BigDecimal(s);
            totalPrice = totalPrice.add(bigDecimal);
        }

        RowRenderData row4 = Rows.of("总价", "", "", "", totalPrice.toString()).center().create();
        rowRenderData[rowRenderData.length - 1] = row4;
        // 表格合并,根据坐标
        MergeCellRule rule = MergeCellRule.builder().map(MergeCellRule.Grid.of(0, 0), MergeCellRule.Grid.of(1, 0)).
                map(MergeCellRule.Grid.of(0, 1), MergeCellRule.Grid.of(1, 1)).
                map(MergeCellRule.Grid.of(0, 2), MergeCellRule.Grid.of(0, 3)).
                map(MergeCellRule.Grid.of(0, 4), MergeCellRule.Grid.of(1, 4)).
                map(MergeCellRule.Grid.of(rowRenderData.length - 1, 0), MergeCellRule.Grid.of(rowRenderData.length - 1, 3)).
                build();

        TableRenderData table = Tables.of(rowRenderData).mergeRule(rule).create();
        // 数据封装
        tableData.setTable(table);
        // 传入模板模板地址+信息数据
        XWPFTemplate template = XWPFTemplate.compile(wordPath).render(tableData);
        OutputStream out = new FileOutputStream(new File("D://价格.docx"));
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(out);
        bos.flush();
        out.flush();
        template.close();
        out.flush();
        bos.close();


//        // 指定下载的文件名--设置响应头
//        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("附件1-报价明细表.docx", "UTF-8"));
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        try {
//            OutputStream out = response.getOutputStream();
//            BufferedOutputStream bos = new BufferedOutputStream(out);
//            template.write(out);
//            bos.flush();
//            out.flush();
//            template.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    public TableRenderData createTable(TableData tableData, String[][] strings){

        for (int i = 0; i < 6; i++) {
            strings[i] = new String[]{"松澧院", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2"};
        }
        tableData.setTableList(strings);
        // 手绘表格
        // 表头
        RowRenderData row0 = Rows.of("项目", "项目1","", "项目2","", "项目3","", "项目4","", "项目5","", "项目6","", "项目7","").center().textFontSize(14).create();
        RowRenderData row1 = Rows.of("","本周","累计","本周","累计","本周","累计","本周","累计","本周","累计","本周","累计","本周","累计").center().textFontSize(14).create();

        int length = 0;
        if (tableData.getTableList() != null) {
            length = tableData.getTableList().length;
        }
        // 表格数据 加上2行表头 再加上最后一行总价
        RowRenderData[] rowRenderData = new RowRenderData[length + 3];
        rowRenderData[0] = row0;
        rowRenderData[1] = row1;
        // 累计数量
        BigDecimal num1 = new BigDecimal("0");
        BigDecimal num2 = new BigDecimal("0");
        BigDecimal num3 = new BigDecimal("0");
        BigDecimal num4 = new BigDecimal("0");
        BigDecimal num5 = new BigDecimal("0");
        BigDecimal num6 = new BigDecimal("0");
        BigDecimal num7 = new BigDecimal("0");
        BigDecimal num8 = new BigDecimal("0");
        BigDecimal num9 = new BigDecimal("0");
        BigDecimal num10 = new BigDecimal("0");
        BigDecimal num11 = new BigDecimal("0");
        BigDecimal num12 = new BigDecimal("0");
        BigDecimal num13 = new BigDecimal("0");
        BigDecimal num14 = new BigDecimal("0");

        for (int i = 0; i < length; i++) {
            rowRenderData[i + 2] = Rows.of(tableData.getTableList()[i]).center().textFontSize(14).create();
            BigDecimal bigDecimal=new BigDecimal(0.00);
            for(int a = 1; a < 15; a++){
               String num= tableData.getTableList()[i][a];
               bigDecimal=new BigDecimal(num) ;
                if(a==1){
                    num1 = num1.add(bigDecimal);
                }else if(a==2){
                    num2 = num2.add(bigDecimal);
                }else if(a==3){
                    num3 = num3.add(bigDecimal);
                }else if(a==4){
                    num4 = num4.add(bigDecimal);
                }else if(a==5){
                    num5 = num5.add(bigDecimal);
                }else if(a==6){
                    num6 = num6.add(bigDecimal);
                }else if(a==7){
                    num7 = num7.add(bigDecimal);
                }else if(a==8){
                    num8 = num8.add(bigDecimal);
                }else if(a==9){
                    num9 = num9.add(bigDecimal);
                }else if(a==10){
                    num10 = num10.add(bigDecimal);
                }else if(a==11){
                    num11 = num11.add(bigDecimal);
                }else if(a==12){
                    num12 = num12.add(bigDecimal);
                }else if(a==13){
                    num13 = num13.add(bigDecimal);
                }else if(a==14){
                    num14 = num14.add(bigDecimal);
                }
            }
        }

        RowRenderData row4 = Rows.of("总计", num1.toString(), num2.toString(), num3.toString(),num4.toString(),num5.toString()
                ,num6.toString(),num7.toString(),num8.toString(),num9.toString(),num10.toString(),num11.toString()
                ,num12.toString(),num13.toString(),num14.toString()).center().textFontSize(14).create();
        rowRenderData[rowRenderData.length - 1] = row4;
        /**
         * 设置表格合并规则
         * 1.起始行 MergeCellRule.Grid.of(i, j) i: 行 j: 列
         * 2.结束行 MergeCellRule.Grid.of(i, j) i: 行 j: 列
         */
        MergeCellRule rule = MergeCellRule.builder().
                map(MergeCellRule.Grid.of(0, 0), MergeCellRule.Grid.of(1, 0)).
                map(MergeCellRule.Grid.of(0, 1), MergeCellRule.Grid.of(0, 2)).
                map(MergeCellRule.Grid.of(0, 3), MergeCellRule.Grid.of(0, 4)).
                map(MergeCellRule.Grid.of(0, 5), MergeCellRule.Grid.of(0, 6)).
                map(MergeCellRule.Grid.of(0, 7), MergeCellRule.Grid.of(0, 8)).
                map(MergeCellRule.Grid.of(0, 9), MergeCellRule.Grid.of(0, 10)).
                map(MergeCellRule.Grid.of(0, 11), MergeCellRule.Grid.of(0, 12)).
                map(MergeCellRule.Grid.of(0, 13), MergeCellRule.Grid.of(0, 14)).
//                map(MergeCellRule.Grid.of(rowRenderData.length - 1, 0), MergeCellRule.Grid.of(rowRenderData.length - 1, 3)).
                build();

        TableRenderData table = Tables.of(rowRenderData).mergeRule(rule).create();

        return table;
    }

    @GetMapping(value = "/weekReport")
    @SneakyThrows
    public void weekReport(TableData tableData, HttpServletResponse response) {
        // 模版路径
        String wordPath = getTemplateAbsolutePath("templates/周报报告信息化模板（3.20）.docx");

        /* 写入数据 */
        tableData.setNo("01");
        tableData.setYear("2023");
        tableData.setMonth("04");
        tableData.setDay("10");
        tableData.setTest("文档描述");
        String[][] strings = new String[6][15];
        TableRenderData table=createTable(tableData,strings);

        // 数据封装
        tableData.setTable(table);
        // 传入模板模板地址+信息数据
        XWPFTemplate template = XWPFTemplate.compile(wordPath).render(tableData);
        OutputStream out = new FileOutputStream(new File("D://周报报告信息化模板（3.20）.docx"));
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(out);
        bos.flush();
        out.flush();
        template.close();
        out.flush();
        bos.close();

    }


    /***
     * 功能描述:
     * 测试文件加水印
     * @Date: 2022-12-01 09:21:25
     * @return: void
     * @since: 1.0.0
     */
    @RequestMapping("/waterMark")
    public void waterMark(){
        String markText = "atk-waterMark "+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String oldFile = "D://work//demo.doc";
        String newFile = "D://work//demo1.doc";
        String oldFile2 = "D://work//尚硅谷技术课程系列之Git V2.0.pdf";
        String newFile2 = "D://work//尚硅谷技术课程系列之Git V2.0水印.pdf";
        String oldFile3 = "D:/work/xlsx文件.xlsx";
        String newFile3 = "D:/work/xlsx文件-水印.xlsx";

//        OfficeWaterMarkUtil.addWordWaterMark(oldFile,newFile,markText);
        OfficeWaterMarkUtil.addPDFWaterMark(oldFile2,newFile2,markText);
//        OfficeWaterMarkUtil.setExcelWaterMark(oldFile3,newFile3,markText);

    }

    /**
     * 功能描述:
     * 获取resource目录下的文件位置
     * @Date: 2023-02-03 09:36:35
     * @Param  templateFileName:
     * @return: java.lang.String
     * @since: 1.0.0
     */
    public String getTemplateAbsolutePath(String templateFileName) throws Exception {
        //注意getResource("")里面是空字符串
        String path = this.getClass().getClassLoader().getResource(templateFileName).getPath();
        System.out.println(path);
        //如果路径中带有中文会被URLEncoder,因此这里需要解码
        String filePath = URLDecoder.decode(path.substring(1,path.length()), "UTF-8");
        System.out.println(filePath);
        return filePath;
    }

}
